package tn.orange.canreminder.service;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;

import tn.orange.canreminder.conf.Config;
import tn.orange.canreminder.parse.GenericJsonParser;

public class RatingServiceImp implements RatingService {

	GenericJsonParser parser = new GenericJsonParser();

	/* (non-Javadoc)
	 * @see tn.orange.canreminder.service.RatingService#getRatingbyId(int)
	 */
	@Override
	public String getRatingbyId(int id) throws Exception {
		// TODO Auto-generated method stub
		HttpClient httpclient = new DefaultHttpClient();
		HttpResponse response = httpclient.execute(new HttpGet(Config.rating
				+ id + ""));
		StringBuilder rating = inputStreamToString(response.getEntity()
				.getContent());
		String resultat = rating.toString().replaceAll("<[^<]*>", "");
		resultat = resultat.replaceAll(" ", "");
		return resultat;

	}

	private StringBuilder inputStreamToString(InputStream is)
			throws IOException {
		String line = "";
		StringBuilder total = new StringBuilder();

		// Wrap a BufferedReader around the InputStream
		BufferedReader rd = new BufferedReader(new InputStreamReader(is));

		// Read response until the end
		while ((line = rd.readLine()) != null) {
			total.append(line);
		}

		// Return full string
		return total;
	}
}
